package com.itheima.controller.backend.check;

import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.AliOssUtil;
import com.itheima.pojo.Pageinfo;
import com.itheima.pojo.Setmeal;
import com.itheima.service.backend.SetMealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/setmeal")
public class SetMealController {
    @Autowired
    private SetMealService setMealService;
    @Autowired
    AliOssUtil aliOssUtil;

    @GetMapping("/findById")
    public Result findById(@RequestParam Integer id){
        log.info("根据id查询套餐, id:{}",id);
        Setmeal setmeal = setMealService.findById(id);
        return new Result(true,"查询成功",setmeal);
    }



    @PostMapping("/findPage")
    public PageResult page(@RequestBody Pageinfo pageinfo){
        Integer page = pageinfo.getCurrentPage();
        Integer pageSize = pageinfo.getPageSize();
        String name = pageinfo.getQueryString();
        log.info("分页查询, 参数: {},{},{},{},{},{}",page,pageSize,name);
        //调用service分页查询
        PageResult pageResult = setMealService.page(page,pageSize,name);
        return pageResult;
    }

    @PostMapping("/upload")
    public Result upload(MultipartFile imgFile){
        log.info("上传图片, 参数: {}",imgFile);
        String url= null;
        try {
            String originalFilename = imgFile.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName= UUID.randomUUID().toString()+extension;
            url = aliOssUtil.upload(imgFile.getBytes(),objectName);
            return new Result(true,"上传成功",url);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
